﻿using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace BambuBusParser
{
    internal class Program
    {
        [STAThread]
        private static void Main(string[] args)
        {
            foreach (string filePath in OpenFileDialog.Show("", true))
            {
                var filename = Path.GetFileNameWithoutExtension(filePath);
                var csvOutputPath = @$"{filename}.csv";
                var binaryOutputPath = @$"{filename}.bin";
                (Memory<byte> memory, var logTimes) = ProcessHexData(filePath);
                var packets = new List<BambubusPacket>();
                for (var i = 0; i < memory.Length; i++)
                {
                    if (memory.Span[i] == 0x3D)
                    {
                        var logTime = logTimes[0].Item2;
                        foreach (var time in logTimes)
                        {
                            if (time.Item1 > i)
                                break;
                            logTime = time.Item2;
                        }

                        var packet = new BambubusPacket(memory.Slice(i));
                        packet.Time = logTime;
                        //Console.WriteLine(packet);
                        packets.Add(packet);
                        i += packet.Length;
                    }
                }

                ExportPacketsToCsv(packets, csvOutputPath);
                File.WriteAllBytes(binaryOutputPath, memory.ToArray());
            }
        }

        private static (byte[], List<Tuple<int, string>>) ProcessHexData(string filePath)
        {
            var logHours = Regex.Match(Path.GetFileNameWithoutExtension(filePath), @"\d{4}-\d{2}-\d{2}").Value;
            string[] lines;
            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var sr = new StreamReader(fs))
            {
                var content = sr.ReadToEnd();
                lines = content.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            }

            var result = new List<byte>();
            var logTimes = new List<Tuple<int, string>>();
            foreach (var line in lines)
            {
                var logMinutes = Regex.Match(line, @"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}");
                if (logMinutes.Success)
                {
                    logTimes.Add(new Tuple<int, string>(result.Count, logMinutes.Value));
                }
                else
                {
                    logTimes.Add(new Tuple<int, string>(result.Count, logHours + " 00:00:00"));
                }

                var hexData = Regex.Replace(Regex.Replace(line, "---.+?---", ""), @"[\s|\r|\n]", "");

                var rawData = Enumerable.Range(0, hexData.Length / 2)
                    .Select(i => Convert.ToByte(hexData.Substring(i * 2, 2), 16))
                    .ToArray();
                result.AddRange(rawData);
            }

            return (result.ToArray(), logTimes);
        }

        private static void ExportPacketsToCsv(List<BambubusPacket> packets, string csvPath)
        {
            using var writer = new StreamWriter(csvPath, false, Encoding.UTF8);
            // 写入CSV标题行
            writer.WriteLine(
                "Time,PackageType,SourceAddress,TargetAddress,AddrFromName,AddrToName,CommandName,AMSNum,ReadNum,FlimentMotion,State,IsInitiator,WantsResponse,FilamentId,FilamentName,RawData");

            // 写入每个数据包的内容
            foreach (var packet in packets)
            {
                writer.WriteLine(
                    $"{packet.Time},{packet.Package},\"0x{packet.SourceAddress:X}\",\"0x{packet.TargetAddress:X}\",\"{packet.AddrFromName}\",\"{packet.AddrToName}\",\"{packet.CommandName}\",\"0x{packet.AMSNum:X}\",\"0x{packet.ReadNum:X}\",\"0x{packet.FlimentMotion:X}\",\"0x{packet.State:X}\",{packet.IsInitiator},{packet.WantsResponse},{packet.FilamentId},{packet.FilamentName},{(BitConverter.ToString(packet.RawData.Span.ToArray()).Replace("-", " "))}");
            }
        }
    }
}